/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ivanbiz.helper;

import com.ivanbiz.dao.AksesMatrixDAO;
import com.ivanbiz.dao.MenuAksesDAO;
import com.ivanbiz.dao.impl.AksesMatrixDAOImpl;
import com.ivanbiz.dao.impl.MenuAksesDAOImpl;
import com.ivanbiz.model.AksesMatrix;
import com.ivanbiz.model.User;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;

/**
 *
 * @author Administrator
 */
public class TreeMenu extends JTree {

    MenuAksesDAO menuAksesDAO = new MenuAksesDAOImpl();
    AksesMatrixDAO aksesMatrixDAO = new AksesMatrixDAOImpl();
    User user = UserSession.getUser();

    public TreeMenu() {
        try {
            List list = menuAksesDAO.getDataByEquals(AksesMatrix.class, "groups.id", user.getGroups().getId());
            Object[] menu = new Object[list.size() + 1];
            menu[0] = "";
            for (int x = 0; x < list.size(); x++) {
                AksesMatrix aksesMatrix = (AksesMatrix) list.get(x);
                menu[x + 1] = aksesMatrix.getMenuAkses().getNama();
            }
            Arrays.sort(menu);
            TreeModel treeModels = new DefaultTreeModel(processHierarchy(menu));
            this.setModel(treeModels);
            this.setScrollsOnExpand(true);
        } catch (Exception ex) {
            Logger.getLogger(TreeMenu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);
        DefaultMutableTreeNode child;
        for (int i = 1; i < hierarchy.length; i++) {
            Object nodeSpecifier = hierarchy[i];
            if (nodeSpecifier instanceof Object[]) {
                child = processHierarchy((Object[]) nodeSpecifier);
            } else {
                child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
            }
            node.add(child);
        }
        return (node);
    }
}
